import datetime
import json
import os
import uuid
import xlrd
from django.core.paginator import Paginator
from django.db.models import Q

from django.http import HttpResponse, JsonResponse

from baseinfo.helpfun import etdata_dict_to_model, query_to_list, etdata_filter, etdata_to_excel, dist_to_string
from baseinfo.models import Outage
from etdata.models import Tank, Etdata


def get_tanks(request):
    if request.method == 'GET':
        outage_name = request.GET.get('outage')
        if outage_name:
            base = outage_name[0:2]
            tanks = Tank.objects.filter(base=base).values('name').distinct()
        else:
            tanks = Tank.objects.all().values('name').distinct()
        tanks_list = []
        for tank in tanks:
            tanks_list.append(tank['name'])
        res = {
            'data': {'tanks': tanks_list},
            'meta': {'status': 200, 'message': '获取容器列表成功'}
        }
        return JsonResponse(res)


def get_tanks2(request):
    if request.method == 'GET':
        if request.GET.get('outages'):
            outages = request.GET.get('outages').split('-')
            base_list = []
            for outage in outages:
                base_list.append(outage[0:2])
            tanks = Tank.objects.filter(base__in=base_list).values('name').distinct()
        else:
             tanks = Tank.objects.all().values('name').distinct()
        tanks_list = []
        for tank in tanks:
            tanks_list.append(tank['name'])
        res = {
            'data': {'tanks': tanks_list},
            'meta': {'status': 200, 'message': '获取容器列表成功'}
        }
        return JsonResponse(res)

# 处理上传涡流数据excel表的处理函数
def upload_etdata(request):
    if request.method == "POST":
        file = request.FILES.get("etdataExcel")
        outage = request.POST.get("outage")
        tank = request.POST.get("tank")
        shortpath = os.path.join('media/etdatatemp', uuid.uuid4().hex + file.name)
        with open(shortpath, 'wb') as temp_file:
            for chunk in file:
                temp_file.write(chunk)
            temp_file.flush()

        wb = xlrd.open_workbook(shortpath)
        ws = wb.sheet_by_index(0)
        titles = ws.row_values(0)
        if titles[1] == 'ID' and titles[2] == 'ZONE' and titles[3] == 'ROW' and titles[4] == 'COL' \
                and titles[5] == 'CAL' and len(titles) == 25:
            pass
        else:
            res = {
                'data': {},
                'meta': {'status': 201, 'message': '表格格式错误'}
            }
            print(res)
            return JsonResponse(res)
        nrows = ws.nrows
        etdatas = []
        total = nrows - 1
        repeat = 0
        new = 0
        for i in range(1, nrows):
            etdata = {}
            etdata['outage'] = outage
            etdata['tank'] = tank
            row_values = ws.row_values(i)
            etdata['zone'] = row_values[2]
            etdata['row'] = int(row_values[3])
            etdata['col'] = int(row_values[4])
            etdata['cal'] = row_values[5]
            etdata['ext'] = row_values[6]
            etdata['leg'] = row_values[7]
            etdata['code'] = row_values[8]
            etdata['volt'] = '' if row_values[9] == '' else float(row_values[9])
            etdata['ph'] = '' if row_values[10] == '' else int(row_values[10])
            etdata['ch'] = row_values[11]
            etdata['percent'] = '' if row_values[12] == '' else int(row_values[12])
            etdata['sup'] = row_values[13]
            etdata['dist'] = '' if row_values[14] == '' else int(row_values[14])
            etdata['sup2'] = row_values[15]
            etdata['dist2'] = '' if row_values[16] == '' else int(row_values[16])
            etdata['long'] = row_values[17]
            etdata['probe'] = row_values[18]
            etdata['arc'] = row_values[19]
            etdata['noise'] = row_values[20]
            etdata['analyst'] = row_values[21]
            etdata['date'] = '' if row_values[22] == '' else xlrd.xldate.xldate_as_datetime(row_values[22] ,0)
            etdata['analysis'] = row_values[23]
            etdata['priority'] = '' if row_values[24] == '' else int(row_values[24])
            # 判断该条数据是否已经存在
            con = Q()
            q1 = Q(outage=outage)
            q2 = Q(tank=tank)
            q3 = Q(zone=etdata['zone'])
            q4 = Q(row=etdata['row'])
            q5 = Q(col=etdata['col'])
            q6 = Q(code=etdata['code'])
            q7 = Q(dist=etdata['dist'])
            con.add(q1, 'AND')
            con.add(q2, 'AND')
            con.add(q3, 'AND')
            con.add(q4, 'AND')
            con.add(q5, 'AND')
            con.add(q6, 'AND')
            con.add(q7, 'AND')
            result = Etdata.objects.filter(con)
            if result.count():
                repeat = repeat + 1
                etdata['is_new'] = 0
            else:
                new = new + 1
                etdata['is_new'] = 1
            etdatas.append(etdata)
        os.remove(shortpath)
        res = {
            'data': {'etdatas': etdatas, 'total': total, 'repeat': repeat, 'new': new},
            'meta': {'status': 200, 'message': '上传成功'}
        }
        return JsonResponse(res)

# 确认上传etdata
def add_etdata(request):
    if request.method == 'POST':
        etdatas = json.loads(request.body).get('etdatas')
        repeat = 0
        new = 0
        for etdata in etdatas:
            if etdata['is_new'] == 1:
                new_etdata = etdata_dict_to_model(etdata)
                new_etdata.save()
                new = new + 1
            else:
                repeat = repeat + 1
        res = {
            'data': {'repeat': repeat, 'new': new},
            'meta': {"status": 200, "message": "数据添加成功"}
        }
        return JsonResponse(res)

# 涡流数据查询请求
def get_etdata(request):
    if request.method == 'POST':
        query = json.loads(request.body)
        # print(query)
        etdatas_query = etdata_filter(query)
        total = etdatas_query.count()
        # 以下为分页部分
        if total:
            pagenum = query.get('pagenum')
            pagesize = query.get('pagesize')
            paginator = Paginator(etdatas_query, pagesize)
            num_pages = paginator.num_pages
            if pagenum > num_pages:
                pagenum = 1
            page_etdata_query = paginator.page(pagenum)
            etdatas = query_to_list(page_etdata_query)
            for etdata in etdatas:
                etdata['dist'] = dist_to_string(etdata['dist'])
            res = {
                'data': {"etdatas": etdatas, "total": total, 'pagenum': pagenum},
                'meta': {'status': 200, 'message': "获取涡流数据成功"}
            }
        else:
            res = {
                'data': {},
                'meta': {'status': 201, 'message': "未查询到数据"}
            }
        return JsonResponse(res)

# 涡流数据查询结果导出excel
def etdata_export_excel(request):
    if request.method == 'POST':
        query = json.loads(request.body)
        etdatas_query = etdata_filter(query)
        excel_url = etdata_to_excel(etdatas_query)
        res = {
            'data': {'excel_url': excel_url},
            'meta': {'status': 200, 'message': '涡流数据查询结果导出成功！'}
        }
        return JsonResponse(res)
